﻿using System;
using Microsoft.Xna.Framework;

namespace Phoenix.Xna.Framework.Components
{
    public abstract class DrawableComponent : Component, IDrawableComponent
    {
        private int _drawOrder;

        public DrawableComponent()
            : base()
        {
            Visible = true;
        }

        public DrawableComponent(string id)
            : base(id)
        {
            Visible = true;
        }

        protected override void Dispose(bool disposing)
        {
            if (!IsDisposed && disposing)
            {
                UnloadContent();
            }

            base.Dispose(true);
        }

        #region IDrawableComponent Members

        public event EventHandler<DrawOrderChangedEventArgs> DrawOrderChanged;

        public bool Visible { get; set; }
        public int DrawOrder
        {
            get { return _drawOrder; }
            set
            {
                if (_drawOrder != value)
                {
                    int oldValue = _drawOrder;
                    _drawOrder = value;
                    EventHandler<DrawOrderChangedEventArgs> handler = DrawOrderChanged;

                    if (handler != null)
                    {
                        handler(this, new DrawOrderChangedEventArgs(oldValue, _drawOrder));
                    }
                }
            }
        }

        public virtual void Draw(GameTime gameTime)
        {
            if (Visible)
            {
                SubComponents.Draw(gameTime);
            }
        }

        #endregion

        #region IHasContent Members

        public bool IsContentLoaded { get; protected set; }

        public virtual void LoadContent()
        {
            if (!IsContentLoaded)
            {
                SubComponents.LoadContent();
                IsContentLoaded = true;
            }
        }

        public virtual void UnloadContent()
        {
            if (IsContentLoaded)
            {
                SubComponents.UnloadContent();
                IsContentLoaded = false;
            }
        }

        #endregion
    }
}
